<template>
    <view class="content">
        <!-- 地图与绘制控件 -->
        <view class="map-wrapper">
            <map
                id="map"
                :latitude="latitude"
                :longitude="longitude"
                :scale="3"
                :max-scale="30"
                :markers="in_view_markers"
                :polygons="polygons"
                :enable-satellite="enableSatellite"
                class="map-container"
            ></map>
            <!-- 中心红色十字 -->
            <view v-if="showCross" class="cross"></view>
            <!-- 地图覆盖切换按钮 -->
            <button class="cross-toggle-btn" @click="toggleCross">
                {{ showCross ? '隐藏十字' : '显示十字' }}
            </button>
        </view>

        <!-- 任务发布边栏 -->
        <view class="sidebar">
            <!-- 新：动态坐标列表 -->
            <view class="section">
                <text class="label">坐标列表</text>
                <view v-for="(pt, idx) in coordList" :key="idx" class="coord-row">
                    <text class="pt-label">点{{ idx + 1 }}</text>
                    <picker mode="selector" :range="['N','S']"
                            :value="pt.latDir==='N'?0:1"
                            @change="onLatDirChange(idx, $event)">
                        <view class="picker-dir">{{ pt.latDir }}</view>
                    </picker>
                    <input v-model="pt.latitude" placeholder="纬度" type="number"/>
                    <picker mode="selector" :range="['E','W']"
                            :value="pt.lonDir==='E'?0:1"
                            @change="onLonDirChange(idx, $event)">
                        <view class="picker-dir">{{ pt.lonDir }}</view>
                    </picker>
                    <input v-model="pt.longitude" placeholder="经度" type="number"/>
                    <!-- 新：填入当前中心位置 -->
                    <button class="use-center-btn" @click="useCenter(idx)">当前位置</button>
                    <button class="remove-btn" @click="removePoint(idx)">×</button>
                </view>
                <button class="add-btn" @click="addPoint">＋</button>
            </view>

            <!-- 新：绘制多边形按钮，移至任务类型前，占满整行 -->
            <button class="draw-btn" @click="drawPolygon">绘制多边形</button>
            <!-- 新：清除绘制按钮 -->
            <button class="clear-btn" @click="clearDrawing">清除绘制</button>

            <view class="section">
                <text class="label">任务类型</text>
                <picker mode="selector" :range="taskTypes"
                        :value="taskTypeIndex"
                        @change="onTaskTypeChange">
                    <view class="picker">{{ taskTypes[taskTypeIndex] }}</view>
                </picker>
            </view>
            <view class="section">
                <text class="label">时间窗口</text>
                <picker mode="selector" :range="timeWindows"
                        :value="timeWindowIndex"
                        @change="onTimeWindowChange">
                    <view class="picker">{{ timeWindows[timeWindowIndex] }}</view>
                </picker>
            </view>

            <button class="publish-btn" @click="publishTask">发布任务</button>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                title: 'Hello',
                latitude: 39.908823,  // 默认纬度，请替换为实际需要的值
                longitude: 116.397470, // 默认经度，请替换为实际需要的值
                in_view_markers: [],    // 地图上的标记
                circles: [],  // 地图上的圆形
                enableSatellite: true, // 是否启用卫星视图
                taskTypes: ['测绘', '巡检', '应急'],      // 任务类型列表
                taskTypeIndex: 0,                        // 选中的类型索引
                timeWindows: ['紧急', '常规'],            // 时间窗口选项
                timeWindowIndex: 0,                      // 默认选中第一个
                polygons: [],            // 多边形展示
                coordList: [                       // 动态点列表
                    { latDir: 'N', latitude: '', lonDir: 'E', longitude: '' }
                ],
                showCross: false   // 控制十字显示
            }
        },
        onLoad() {

        },
        methods: {
            publishTask() {
                console.log('发布任务', {
                    type: this.taskTypes[this.taskTypeIndex],
                    timeWindow: this.timeWindows[this.timeWindowIndex]
                });
                // TODO: 调用后端接口发布任务
            },
            addPoint() {
                this.coordList.push({ latDir: 'N', latitude: '', lonDir: 'E', longitude: '' });
            },
            removePoint(i) {
                this.coordList.splice(i, 1);
            },
            // 先清空视图，再异步下一轮中绘制新图
            async drawPolygon() {
                this.clearDrawing();
                await this.$nextTick();
                const pts = this.coordList.map(pt => {
                    const lat = parseFloat(pt.latitude) * (pt.latDir === 'N' ? 1 : -1);
                    const lng = parseFloat(pt.longitude) * (pt.lonDir === 'E' ? 1 : -1);
                    if (isNaN(lat) || isNaN(lng)) throw new Error();
                    return { latitude: lat, longitude: lng };
                });
                this.in_view_markers = pts.map((p, i) => ({
                    id: i, latitude: p.latitude, longitude: p.longitude,
                    iconPath: '/static/point.png', width: 10, height: 10
                }));
                this.polygons = [{
                    points: pts,
                    strokeWidth: 2, strokeColor: '#FF0000',
                    fillColor: '#0000FF33', zIndex: 1, level: 'abovelabels'
                }];
            },
            // 新：清除绘制方法
            clearDrawing() {
                this.in_view_markers = [];
                this.polygons = [];
            },
            toggleCross() {
                this.showCross = !this.showCross;
            },
            // 填入当前地图中心位置
            useCenter(i) {
                const mapCtx = uni.createMapContext('map');
                mapCtx.getCenterLocation({
                    success: ({ latitude, longitude }) => {
                        this.coordList[i].latDir = latitude >= 0 ? 'N' : 'S';
                        this.coordList[i].lonDir = longitude >= 0 ? 'E' : 'W';
                        this.coordList[i].latitude = Math.abs(latitude).toFixed(6);
                        this.coordList[i].longitude = Math.abs(longitude).toFixed(6);
                    }
                });
            },
            onLatDirChange(i, e) {
                const dirs = ['N','S']
                this.coordList[i].latDir = dirs[e.detail.value]
            },
            onLonDirChange(i, e) {
                const dirs = ['E','W']
                this.coordList[i].lonDir = dirs[e.detail.value]
            },
            onTaskTypeChange(e) {
                this.taskTypeIndex = e.detail.value
            },
            onTimeWindowChange(e) {
                this.timeWindowIndex = e.detail.value
            }
        }
    }
</script>

<style>
    .content {
        display: flex;
        flex-direction: row;       /* 横向布局：左地图右边栏 */
        width: 100%;
        height: 100vh;
        position: relative;
    }

    .map-wrapper {
        position: relative;
        width: 70%;
        height: 100%;
    }

    .controls {
        position: absolute;
        top: 10px;
        left: 10px;
        z-index: 100;
        display: flex;
    }

    .controls button {
        margin-right: 8px;
    }

    /* 修改宽度至100%，移除flex */
    .map-container {
        width: 100%;
        height: 100%;
    }

    .sidebar {
        width: 30%;
        padding: 20rpx;
        background: #f5f5f5;
    }

    .section {
        margin-bottom: 20rpx;
    }

    .label {
        font-size: 28rpx;
        margin-bottom: 10rpx;
    }

    .picker {
        padding: 10rpx;
        background: #fff;
        border-radius: 4rpx;
    }

    .publish-btn {
        width: 100%;
        padding: 20rpx;
        background: #007aff;
        color: #fff;
        text-align: center;
        border-radius: 4rpx;
    }

    .logo {
        height: 200rpx;
        width: 200rpx;
        margin-top: 200rpx;
        margin-left: auto;
        margin-right: auto;
        margin-bottom: 50rpx;
    }

    .text-area {
        display: flex;
        justify-content: center;
    }

    .title {
        font-size: 36rpx;
        color: #8f8f94;
    }

    .draw-btn {
        width: 100%;
        padding: 10rpx;
        font-size: 24rpx;
        background: #28a745;
        color: #fff;
        text-align: center;
        border-radius: 4rpx;
        margin: 10rpx auto;
    }

    /* 新：清除绘制按钮样式 */
    .clear-btn {
        width: 100%;
        padding: 10rpx;
        font-size: 24rpx;
        background: #dc3545;
        color: #fff;
        text-align: center;
        border-radius: 4rpx;
        margin: 10rpx auto;
    }

    .coord-row {
        display: flex; align-items: center; margin-bottom: 10rpx;
    }

    .picker-dir, input {
        width: 120rpx; margin-right: 10rpx; padding: 6rpx; background: #fff; border-radius: 4rpx;
    }

    .remove-btn {
        width: 30rpx; height: 30rpx; line-height: 30rpx; text-align: center; color: #fff;
        background: #e74c3c; border-radius: 15rpx; margin-left: auto;
    }

    .add-btn {
        width: 100%;
        padding: 10rpx 0;         /* 缩小高度 */
        font-size: 32rpx;         /* 略小字体 */
        background: transparent;
        border: none;
        text-align: center;
        margin: 0;
    }

    .add-btn:hover {
        background: #f0f0f0;      /* hover 变灰 */
    }

    .pt-label {
        width: 60rpx;
        margin-right: 10rpx;
        font-size: 28rpx;
        text-align: center;
    }

    /* 增大中心红色十字 */
    .cross {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 40rpx;
        height: 40rpx;
        transform: translate(-50%, -50%);
        pointer-events: none;
    }
    .cross::before,
    .cross::after {
        content: '';
        position: absolute;
        background: red;
    }
    .cross::before {
        left: 50%;
        top: 0;
        width: 4rpx;
        height: 100%;
        transform: translateX(-50%);
    }
    .cross::after {
        top: 50%;
        left: 0;
        width: 100%;
        height: 4rpx;
        transform: translateY(-50%);
    }
    /* 地图覆盖切换按钮样式 */
    .cross-toggle-btn {
        position: absolute;
        top: 10rpx;
        right: 10rpx;
        padding: 8rpx 12rpx;
        background: rgba(0,122,255,0.8);
        color: #fff;
        font-size: 24rpx;
        border-radius: 4rpx;
        z-index: 200;
    }

    /* “当前位置”按钮样式 */
    .use-center-btn {
        padding: 6rpx 10rpx;
        margin-left: 10rpx;
        font-size: 24rpx;
        background: #007aff;
        color: #fff;
        border-radius: 4rpx;
    }
</style>